package com.biodiversitydigit.models
{
	import com.asual.swfaddress.SWFAddress;
	import com.asual.swfaddress.SWFAddressEvent;
	
	import mx.controls.Alert;
	import mx.core.Application;
	import mx.states.State;
	
	
	[Bindable]
	public class StatesModelLocator
	{
		public function StatesModelLocator()
		{   
			if ( com.biodiversitydigit.models.StatesModelLocator.modelLocator != null ) {
                throw new Error( "Only one ModelLocator instance should be instantiated" );        				
			}
            initialize();
		}

        public static function getInstance():StatesModelLocator
        {
            if ( modelLocator == null )
                modelLocator = new StatesModelLocator();
                
            return modelLocator;
       }
       private static var modelLocator:StatesModelLocator;
       
	// END of definition of Singleton       
       
       private function initialize() : void {
       		//Listen to SWFAddress events to change states
			SWFAddress.addEventListener(SWFAddressEvent.INIT, handleSWFAddressInit);
       	
       }       
       
		public var topState:String;
		public var secondState:String;
		public var thirdState:String;
       
       
		private static function handleSWFAddressInit(event:SWFAddressEvent):void {
			SWFAddress.addEventListener(SWFAddressEvent.CHANGE,handleSWFAddressChange);						
		}
		
		private static function handleSWFAddressChange(event:SWFAddressEvent):void {
			
			//get existing states in the app to check if the topLevel in the
			//url
			var _states:Array = new Array();
			for each (var s:State in Application.application.states) {
				_states.push(s.name);
			}
			
			//Check if the URL defines a state or is defined at all.
			if (event.pathNames[0] == undefined) {
				getInstance().topState = AppStates.TOP_START;
				SWFAddress.setValue(AppStates.TOP_START);
			} 
			else if (_states.indexOf(event.pathNames[0])<0 ) {
				getInstance().topState = AppStates.TOP_START;
				SWFAddress.setValue(AppStates.TOP_START);
				Alert.show('You have been redirected to the main page as your URL was wrong');				
			}
			else {
				getInstance().topState = event.pathNames[0];
			}			
			
			(event.pathNames[1])? getInstance().secondState = event.pathNames[1]:getInstance().secondState='';
			(event.pathNames[2])? getInstance().thirdState = event.pathNames[2]: getInstance().thirdState = '';			
			
			
		}
       
       
       
       
       
       

	}
}